//
//  RelationShipViewController.m
//  parent
//
//  Created by 闫珍 on 15/5/19.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "RelationShipViewController.h"
#import "BabyInfoViewController.h"
#import "JsonUtil.h"
#import "NetWorkManager.h"
#import "PopUIManager.h"
#import "UserDao.h"
#import "MainViewCreater.h"

@interface RelationShipViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *relationTableView;
@property (strong,nonatomic) NSArray *ships;
@property (strong,nonatomic) NSIndexPath *lastIndex;
@end

@implementation RelationShipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self customView];
    _ships = @[@"妈妈",@"爸爸",@"爷爷",@"奶奶",@"外公",@"外婆",@"姥姥",@"姥爷",@"其他关系"];
    _relationTableView.sectionFooterHeight = 1.0;
    _relationTableView.sectionHeaderHeight = 1.0;
    self.lastIndex = nil;
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1.0;
}


-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"选择与宝贝的关系";
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    self.navigationItem.rightBarButtonItem
    =[[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(nextStep:)];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _ships.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"simple"];
    if(cell==nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"simple"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    NSString *title = [_ships objectAtIndex:indexPath.row];
    cell.textLabel.text = title;
   
    if ([indexPath compare:self.lastIndex] == NSOrderedSame)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    if(indexPath.row == 0 && self.lastIndex ==nil){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.lastIndex = indexPath;
    [self.relationTableView reloadData];
}

-(void)nextStep:(id)sender
{
    if(![_inviteCode isEqualToString:@""]&&_inviteCode.length>0){
        //直接进入
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:_phoneNum, @"phone",
                                     _password, @"pwd",
                                     _nickname, @"nickname",
                                     @(self.lastIndex.row+1), @"frole",
                                     _avatar,@"avatar",
                                     _inviteCode,@"invite_code",
                                     nil];
        NSString *dataString = [JsonUtil convertDictionaryToJson:dict];
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [popUIMgr showWaitingUI:self.view];
        
        [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_REGISTER data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            [popUIMgr removeWaitingUI];
            if (connectionError) { //连接失败
                debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    debugLog(@"数据字典: %@", dict);
                    
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        NSString *ret_msg;
                        switch ([[dict objectForKey:@"retCode"] integerValue]) {
                            case 1:
                            {
                                ret_msg= @"Success";
                                break;
                            }
                            case 10005:{
                                ret_msg= @"注册失败";
                                break;
                            }
                            case 10007:{
                                ret_msg =@"用户已经存在";
                                break;
                            }
                            case 10015:{
                                ret_msg=@"验证码不存在";
                                break;
                            }
                                
                        }
                        if (![ret_msg isEqual:@"Success"]) {
                            [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                            return;
                        }else{
                            //注册成功
                            debugLog(@"%@",dict);
                            //保存用户数据
                            BOOL result = [[UserDao getInstance]saveUserData:dict];
                            NSArray *babyinfo = [dict objectForKey:@"babyinfo"];
                            if(babyinfo!=nil && babyinfo.count>0){
                                for (NSDictionary* dicc in babyinfo) {
                                    [[BabyDao getInstance]saveBabyData:dicc];
                                }
                            }
                            if(result){
                                UIViewController *mainViewController = [[MainViewCreater getInstance]createMainView];
                               
                                UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                                window.rootViewController = mainViewController;

                            }
                            
                        }
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                        return;
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                    return;
                }
            }
            
        }];

        
    }else{
        BabyInfoViewController *babyInfo = [[BabyInfoViewController alloc]init];
        babyInfo.phoneNum = _phoneNum;
        babyInfo.nickname = _nickname;
        babyInfo.password = _password;
        babyInfo.avatar = _avatar;
        babyInfo.inviteCode = _inviteCode;
        babyInfo.frole = self.lastIndex.row +1;
        [self.navigationController pushViewController:babyInfo animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
